package com.mgs.tagger.appdata
{
	import com.mgs.tagger.appdata.dto.DirectoryDTO;
	import com.mgs.tagger.appdata.dto.FileItemDTO;
	import com.mgs.tagger.appdata.dto.TagDTO;
	import com.mgs.tagger.appdata.dto.WorkspaceDTO;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.registerClassAlias;

	public class PersistenceManager
	{
		private static var _instance:PersistenceManager;
		
		public static function get instance():PersistenceManager{
			if(_instance == null){
				_instance = new PersistenceManager();
			}
			return _instance;
		}
		
		private static const PREFERENCE_FILE:String = "preferences.dat";
		private var registered:Boolean = false;
		
		function PersistenceManager()
		{
		}
		public function load():WorkspaceDTO{
			register();
			var workspace:WorkspaceDTO;
			var file:File = getFile();
			if(file.exists){
				var stream:FileStream = new FileStream();
				stream.open(file, FileMode.READ);
				workspace = stream.readObject() as WorkspaceDTO;
				stream.close();
			}else{
				workspace = new WorkspaceDTO();
				workspace.directories = new Vector.<DirectoryDTO>();
			}
			// patch item size.
			if(workspace.itemSize < ItemSizeConstant.MIN || 
				workspace.itemSize > ItemSizeConstant.MAX){
				workspace.itemSize = ItemSizeConstant.MEDIUM;
			}
			return workspace;
		}
		public function save(workspace:WorkspaceDTO):void{
			register();
			var file:File = getFile();
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.WRITE);
			stream.writeObject(workspace);
			stream.close();
		}
		private function register():void{
			if(!registered){
				registerClassAlias("workspaceDTO", WorkspaceDTO);
				registerClassAlias("DirectoryDTO", DirectoryDTO);
				registerClassAlias("FileItemDTO", FileItemDTO);
				registerClassAlias("TagDTO", TagDTO);
				registered = true;
			}
		}
		private function getFile():File{
			return File.applicationStorageDirectory.resolvePath(PREFERENCE_FILE);
		}
		
	}
}